package com.educhains.web.util;

import javax.servlet.http.HttpServletRequest;

/**
 * @author YuRun
 * @since 2017年8月24日
 */
public class WebUtils extends org.springframework.web.util.WebUtils {

    /**
     * Get request path completed
     *
     * @param request
     * @param requestPath
     * @return
     */
    public static String getRequestPath(HttpServletRequest request, String requestPath) {
        return getRequestPath(request, requestPath, true, false);
    }

    /**
     * Get request path
     *
     * @param request
     * @param requestPath
     * @param completedURL
     * @param withSessionId
     * @return
     */
    public static String getRequestPath(HttpServletRequest request, String requestPath, boolean completedURL, boolean withSessionId) {
        String contextPath = request.getContextPath();
        String serverPrefix = "";
        if (completedURL) {
            serverPrefix = request.getScheme() + "://" + request.getServerName();
            if ((!"http".equalsIgnoreCase(request.getScheme()) || request.getServerPort() != 80) && (!"https".equalsIgnoreCase(request.getScheme()) || request.getServerPort() != 843)) {
                serverPrefix = serverPrefix + ":" + request.getServerPort();
            }
        }

        String url = null;
        if (requestPath != null && requestPath.length() > 0) {
            if (requestPath.charAt(0) == 47) {
                url = serverPrefix + contextPath + requestPath;
            } else {
                url = serverPrefix + contextPath + '/' + requestPath;
            }
        } else {
            url = serverPrefix + contextPath;
        }

        if (withSessionId) {
            url = url + ";jsessionid=" + request.getSession(true).getId();
        }

        return url;
    }
}
